package com.wss.common.wechat.controller;


import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.wss.common.context.util.HttpRequestProxyUtil;
import com.wss.common.context.util.SystemConfig;
import com.wss.common.wechat.util.OpenWeChatInterfaceUtil;
import com.wss.common.wechat.util.weixin.AuthorizeLinkOpenManager;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 赵飞
 * @version V1.0
 * @Title:
 * @Package com.evermotion.common.wechat.controller
 * @Description: 微信三方预授权跳转链接
 * @date 2017/7/14
 */
@Controller
public class OpenPreAuthController {

	private static final Logger logger = Logger.getLogger(OpenPreAuthController.class);

	/**
	 * 进入授权准备页
		 *  http://testcrm.emkol.cn/OpenWeChatManager/open/startAuth.do
	 */
	@RequestMapping(value = "/open/startAuth.do", method =RequestMethod.GET)
	public String startAuth() {
		return "/auth/auth_start";
	}

	/**
	 * 导向微信授权二维码页
	 */
	@RequestMapping(value = "/open/preAuth.do", method =RequestMethod.GET,produces ={"text/html"})
	public void preAuth(HttpServletResponse response) {

		JsonParser jsonParser = new JsonParser();
		//获取微信预授权码
		String jsonStr="";
		try {
			JsonObject jsonParam = new JsonObject();
			jsonParam.addProperty("component_appid", SystemConfig.getComponentAppId());
			jsonStr = HttpRequestProxyUtil.executeJsonParamHttpPost(OpenWeChatInterfaceUtil.getApiCreatePreauthcode(),jsonParam.toString());
			logger.info("获取预授权返回："+jsonStr);
			if(jsonStr!=null&&!"".equals(jsonStr)){
				JsonObject jsonObject = jsonParser.parse(jsonStr).getAsJsonObject();
				if(jsonObject.has("pre_auth_code")){
					response.sendRedirect(AuthorizeLinkOpenManager.getOauthlink(jsonObject.get("pre_auth_code").getAsString()));
				}
			}
		} catch (Exception e) {
			logger.info("获取预授权码出错！返回："+jsonStr,e);
			e.printStackTrace();
		}

	}

	/**
	 * 进入授权完成
	 */
	@RequestMapping(value = "/open/endAuth.do", method =RequestMethod.GET)
	public String endAuth(HttpServletRequest req) {


		return "/auth/auth_end";
	}
}
